from dataclasses import fields

from odoo import models, api, fields
from odoo.exceptions import UserError


class SbMESPartner(models.Model):
    _name = 'res.partner'
    _inherit = ['res.partner', 's.mes.upload']

    def wms_cron_all(self):
        if self.s_check_allow():
            domain = [('code', '!=', False), ('is_company', '=', True), ('id', '>', 0)]
            records = self.env['res.partner'].sudo().search(domain)
            for rec in records:
                rec.wms_partner_upload()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        if self.s_check_allow():
            for rec in result:
                if rec.is_company and rec.code:
                    rec.wms_partner_upload()
        return result

    # def write(self, vals):
    #     res = super().write(vals)
    #     if self.s_check_allow():
    #         for record in self:
    #             if record.is_company and record.code:
    #                 record.with_delay().wms_partner_upload()
    #     return res

    def wms_partner_upload(self):
        """
        客户供应商
        """
        infos = []
        vals = {"reqTime": fields.Datetime.to_string(fields.Datetime.now()), 'Infos': []}
        if self.supplier_rank > 0 or (not self.is_virtual_customer and self.supplier_rank <= 0):
            address = [self.country_id.name, self.city, self.street, self.street2]
            format_address = list(filter(lambda x: x, address))
            infos.append({
                'CompanyID': self.code,
                'CompanyName': self.name,
                'CompanySName': self.short_name,
                'Type': 4 if self.supplier_rank > 0 else 3, # 3 供应商，4 客户
                'Tel': self.mobile if self.mobile else '',
                'Mobile': self.phone if self.phone else '',
                'Email': self.email if self.phone else '',
                'Address': ','.join(format_address),
                'Contacts': '',
            })
        else:
            pass
        if infos:
            vals['Infos'] = infos
            self.wms_upload_data(vals, '/JehaitWS/JOVETG/CustomerData')
